package cn.cangnova.controller.api

import cn.cangnova.model.ApiResponse
import cn.cangnova.services.LogEntry
import cn.cangnova.services.SystemMonitorService
import io.ktor.http.*
import io.ktor.server.auth.*
import io.ktor.server.response.*
import io.ktor.server.routing.*

private val systemMonitorService = SystemMonitorService()

/**
 * 系统监控API路由
 */
fun Route.systemMonitorApiRoutes() {
    // 需要JWT认证
    authenticate("jwt-auth") {
        // 获取所有系统监控数据
        get {
            try {
                val resources = systemMonitorService.getSystemResources()
                val services = systemMonitorService.getServiceStatuses().map { service ->
                    mapOf(
                        "name" to service.name,
                        "status" to service.status.name.lowercase(),
                        "uptime" to service.getUptimeString(),
                        "memory" to service.memoryUsage,
                        "cpu" to service.cpuUsage,
                        "restarts" to service.restartCount
                    )
                }
                val logs = systemMonitorService.getLogs().map { log ->
                    mapOf(
                        "id" to log.id,
                        "timestamp" to log.timestamp,
                        "level" to log.level.name.lowercase(),
                        "service" to log.service,
                        "message" to log.message
                    )
                }
                val networkStats = systemMonitorService.getNetworkStats()
                val storageVolumes = systemMonitorService.getStorageVolumes()
                val databaseStats = systemMonitorService.getDatabaseStats()

                call.respond(
                    HttpStatusCode.OK,
                    ApiResponse(
                        success = true,
                        data = mapOf(
                            "systemResources" to mapOf(
                                "cpu" to resources.cpu,
                                "memory" to resources.memory,
                                "disk" to resources.disk,
                                "status" to resources.status.name.lowercase(),
                                "uptime" to resources.uptime,
                                "lastUpdated" to resources.lastUpdated
                            ),
                            "services" to services,
                            "logs" to logs,
                            "networkStats" to mapOf(
                                "inbound" to networkStats.inbound,
                                "outbound" to networkStats.outbound,
                                "activeConnections" to networkStats.activeConnections,
                                "totalTransferred" to networkStats.totalTransferred,
                                "requestsPerMinute" to networkStats.requestsPerMinute
                            ),
                            "storageVolumes" to storageVolumes.map { volume ->
                                mapOf(
                                    "name" to volume.name,
                                    "usedPercentage" to volume.usedPercentage,
                                    "totalSpace" to volume.totalSpace,
                                    "freeSpace" to volume.freeSpace
                                )
                            },
                            "databaseStats" to mapOf(
                                "connections" to databaseStats.connections,
                                "activeQueries" to databaseStats.activeQueries,
                                "cacheHitRate" to databaseStats.cacheHitRate,
                                "avgQueryTime" to databaseStats.avgQueryTime
                            )
                        ),
                        message = "系统监控数据获取成功"
                    )
                )
            } catch (e: Exception) {
                call.respond(
                    HttpStatusCode.InternalServerError,
                    ApiResponse(
                        success = false,
                        data = null,
                        message = "获取系统监控数据失败: ${e.message}"
                    )
                )
            }
        }

        // 获取系统资源信息
        get("/resources") {
            try {
                val resources = systemMonitorService.getSystemResources()
                call.respond(
                    HttpStatusCode.OK,
                    ApiResponse(
                        success = true,
                        data = mapOf(
                            "cpu" to resources.cpu,
                            "memory" to resources.memory,
                            "disk" to resources.disk,
                            "status" to resources.status.name.lowercase(),
                            "uptime" to resources.uptime,
                            "lastUpdated" to resources.lastUpdated
                        ),
                        message = "系统资源数据获取成功"
                    )
                )
            } catch (e: Exception) {
                call.respond(
                    HttpStatusCode.InternalServerError,
                    ApiResponse(
                        success = false,
                        data = null,
                        message = "获取系统资源数据失败: ${e.message}"
                    )
                )
            }
        }

        // 获取服务状态列表
        get("/services") {
            try {
                val services = systemMonitorService.getServiceStatuses().map { service ->
                    mapOf(
                        "name" to service.name,
                        "status" to service.status.name.lowercase(),
                        "uptime" to service.getUptimeString(),
                        "memory" to service.memoryUsage,
                        "cpu" to service.cpuUsage,
                        "restarts" to service.restartCount
                    )
                }
                call.respond(
                    HttpStatusCode.OK,
                    ApiResponse(
                        success = true,
                        data = services,
                        message = "服务状态列表获取成功"
                    )
                )
            } catch (e: Exception) {
                call.respond(
                    HttpStatusCode.InternalServerError,
                    ApiResponse(
                        success = false,
                        data = null,
                        message = "获取服务状态列表失败: ${e.message}"
                    )
                )
            }
        }

        // 重启服务
        post("/services/{serviceName}/restart") {
            try {
                val serviceName = call.parameters["serviceName"] ?: return@post call.respond(
                    HttpStatusCode.BadRequest,
                    ApiResponse(
                        success = false,
                        data = null,
                        message = "服务名称不能为空"
                    )
                )

                val success = systemMonitorService.restartService(serviceName)
                if (success) {
                    call.respond(
                        HttpStatusCode.OK,
                        ApiResponse(
                            success = true,
                            data = mapOf("success" to true),
                            message = "服务重启成功"
                        )
                    )
                } else {
                    call.respond(
                        HttpStatusCode.NotFound,
                        ApiResponse(
                            success = false,
                            data = null,
                            message = "未找到指定服务"
                        )
                    )
                }
            } catch (e: Exception) {
                call.respond(
                    HttpStatusCode.InternalServerError,
                    ApiResponse(
                        success = false,
                        data = null,
                        message = "重启服务失败: ${e.message}"
                    )
                )
            }
        }

        // 获取系统日志
        get("/logs") {
            try {
                val limit = call.request.queryParameters["limit"]?.toIntOrNull() ?: 100
                val logs = systemMonitorService.getLogs(limit).map { log ->
                    mapOf(
                        "id" to log.id,
                        "timestamp" to log.timestamp,
                        "level" to log.level.name.lowercase(),
                        "service" to log.service,
                        "message" to log.message
                    )
                }
                call.respond(
                    HttpStatusCode.OK,
                    ApiResponse(
                        success = true,
                        data = logs,
                        message = "系统日志获取成功"
                    )
                )
            } catch (e: Exception) {
                call.respond(
                    HttpStatusCode.InternalServerError,
                    ApiResponse(
                        success = false,
                        data = null,
                        message = "获取系统日志失败: ${e.message}"
                    )
                )
            }
        }

        // 获取网络统计数据
        get("/network") {
            try {
                val networkStats = systemMonitorService.getNetworkStats()
                call.respond(
                    HttpStatusCode.OK,
                    ApiResponse(
                        success = true,
                        data = mapOf(
                            "inbound" to networkStats.inbound,
                            "outbound" to networkStats.outbound,
                            "activeConnections" to networkStats.activeConnections,
                            "totalTransferred" to networkStats.totalTransferred,
                            "requestsPerMinute" to networkStats.requestsPerMinute
                        ),
                        message = "网络统计数据获取成功"
                    )
                )
            } catch (e: Exception) {
                call.respond(
                    HttpStatusCode.InternalServerError,
                    ApiResponse(
                        success = false,
                        data = null,
                        message = "获取网络统计数据失败: ${e.message}"
                    )
                )
            }
        }

        // 获取存储卷信息
        get("/storage") {
            try {
                val storageVolumes = systemMonitorService.getStorageVolumes()
                call.respond(
                    HttpStatusCode.OK,
                    ApiResponse(
                        success = true,
                        data = storageVolumes.map { volume ->
                            mapOf(
                                "name" to volume.name,
                                "usedPercentage" to volume.usedPercentage,
                                "totalSpace" to volume.totalSpace,
                                "freeSpace" to volume.freeSpace
                            )
                        },
                        message = "存储卷信息获取成功"
                    )
                )
            } catch (e: Exception) {
                call.respond(
                    HttpStatusCode.InternalServerError,
                    ApiResponse(
                        success = false,
                        data = null,
                        message = "获取存储卷信息失败: ${e.message}"
                    )
                )
            }
        }

        // 获取数据库统计信息
        get("/database") {
            try {
                val databaseStats = systemMonitorService.getDatabaseStats()
                call.respond(
                    HttpStatusCode.OK,
                    ApiResponse(
                        success = true,
                        data = mapOf(
                            "connections" to databaseStats.connections,
                            "activeQueries" to databaseStats.activeQueries,
                            "cacheHitRate" to databaseStats.cacheHitRate,
                            "avgQueryTime" to databaseStats.avgQueryTime
                        ),
                        message = "数据库统计信息获取成功"
                    )
                )
            } catch (e: Exception) {
                call.respond(
                    HttpStatusCode.InternalServerError,
                    ApiResponse(
                        success = false,
                        data = null,
                        message = "获取数据库统计信息失败: ${e.message}"
                    )
                )
            }
        }

        // 添加日志条目
        post("/logs") {
            try {
                // 在实际实现中，我们会解析请求体
                // 现在，只添加一个测试日志条目
                systemMonitorService.addLog(
                    LogEntry.Level.INFO,
                    "API服务",
                    "手动添加的日志条目"
                )
                call.respond(
                    HttpStatusCode.OK,
                    ApiResponse(
                        success = true,
                        data = mapOf("success" to true),
                        message = "日志添加成功"
                    )
                )
            } catch (e: Exception) {
                call.respond(
                    HttpStatusCode.InternalServerError,
                    ApiResponse(
                        success = false,
                        data = null,
                        message = "添加日志失败: ${e.message}"
                    )
                )
            }
        }
    }
}

/**
 * Controller for system monitoring endpoints
 */
class SystemMonitorController(private val systemMonitorService: SystemMonitorService) {

    /**
     * Register routes for system monitoring
     */
    fun registerRoutes(routing: Routing) {
        routing.route("/api/system") {
            // Get all system monitoring data in one call
            get {
                val resources = systemMonitorService.getSystemResources()
                val services = systemMonitorService.getServiceStatuses().map { service ->
                    mapOf(
                        "name" to service.name,
                        "status" to service.status.name.lowercase(),
                        "uptime" to service.getUptimeString(),
                        "memory" to service.memoryUsage,
                        "cpu" to service.cpuUsage,
                        "restarts" to service.restartCount
                    )
                }
                val logs = systemMonitorService.getLogs().map { log ->
                    mapOf(
                        "id" to log.id,
                        "timestamp" to log.timestamp,
                        "level" to log.level.name.lowercase(),
                        "service" to log.service,
                        "message" to log.message
                    )
                }
                val networkStats = systemMonitorService.getNetworkStats()
                val storageVolumes = systemMonitorService.getStorageVolumes()
                val databaseStats = systemMonitorService.getDatabaseStats()

                call.respond(
                    mapOf(
                        "systemResources" to mapOf(
                            "cpu" to resources.cpu,
                            "memory" to resources.memory,
                            "disk" to resources.disk,
                            "status" to resources.status.name.lowercase(),
                            "uptime" to resources.uptime,
                            "lastUpdated" to resources.lastUpdated
                        ),
                        "cn/cangnova/servicesova/services" to services,
                        "logs" to logs,
                        "networkStats" to mapOf(
                            "inbound" to networkStats.inbound,
                            "outbound" to networkStats.outbound,
                            "activeConnections" to networkStats.activeConnections,
                            "totalTransferred" to networkStats.totalTransferred,
                            "requestsPerMinute" to networkStats.requestsPerMinute
                        ),
                        "storageVolumes" to storageVolumes.map { volume ->
                            mapOf(
                                "name" to volume.name,
                                "usedPercentage" to volume.usedPercentage,
                                "totalSpace" to volume.totalSpace,
                                "freeSpace" to volume.freeSpace
                            )
                        },
                        "databaseStats" to mapOf(
                            "connections" to databaseStats.connections,
                            "activeQueries" to databaseStats.activeQueries,
                            "cacheHitRate" to databaseStats.cacheHitRate,
                            "avgQueryTime" to databaseStats.avgQueryTime
                        )
                    )
                )
            }

            // Get system resources
            get("/resources") {
                val resources = systemMonitorService.getSystemResources()
                call.respond(
                    mapOf(
                        "cpu" to resources.cpu,
                        "memory" to resources.memory,
                        "disk" to resources.disk,
                        "status" to resources.status.name.lowercase(),
                        "uptime" to resources.uptime,
                        "lastUpdated" to resources.lastUpdated
                    )
                )
            }

            // Get service statuses
            get("/cn/cangnova/servicesova/services") {
                val services = systemMonitorService.getServiceStatuses().map { service ->
                    mapOf(
                        "name" to service.name,
                        "status" to service.status.name.lowercase(),
                        "uptime" to service.getUptimeString(),
                        "memory" to service.memoryUsage,
                        "cpu" to service.cpuUsage,
                        "restarts" to service.restartCount
                    )
                }
                call.respond(services)
            }

            // Restart a service
            post("/cn/cangnova/services/{serviceName}/restart") {
                val serviceName = call.parameters["serviceName"] ?: return@post call.respond(
                    HttpStatusCode.BadRequest, mapOf("error" to "Service name is required")
                )

                val success = systemMonitorService.restartService(serviceName)
                if (success) {
                    call.respond(mapOf("success" to true, "message" to "Service restarted successfully"))
                } else {
                    call.respond(HttpStatusCode.NotFound, mapOf("error" to "Service not found"))
                }
            }

            // Get logs
            get("/logs") {
                val limit = call.request.queryParameters["limit"]?.toIntOrNull() ?: 100
                val logs = systemMonitorService.getLogs(limit).map { log ->
                    mapOf(
                        "id" to log.id,
                        "timestamp" to log.timestamp,
                        "level" to log.level.name.lowercase(),
                        "service" to log.service,
                        "message" to log.message
                    )
                }
                call.respond(logs)
            }

            // Get network stats
            get("/network") {
                val networkStats = systemMonitorService.getNetworkStats()
                call.respond(
                    mapOf(
                        "inbound" to networkStats.inbound,
                        "outbound" to networkStats.outbound,
                        "activeConnections" to networkStats.activeConnections,
                        "totalTransferred" to networkStats.totalTransferred,
                        "requestsPerMinute" to networkStats.requestsPerMinute
                    )
                )
            }

            // Get storage volumes
            get("/storage") {
                val storageVolumes = systemMonitorService.getStorageVolumes()
                call.respond(storageVolumes.map { volume ->
                    mapOf(
                        "name" to volume.name,
                        "usedPercentage" to volume.usedPercentage,
                        "totalSpace" to volume.totalSpace,
                        "freeSpace" to volume.freeSpace
                    )
                })
            }

            // Get database stats
            get("/cn/cangnova/databaseova/database") {
                val databaseStats = systemMonitorService.getDatabaseStats()
                call.respond(
                    mapOf(
                        "connections" to databaseStats.connections,
                        "activeQueries" to databaseStats.activeQueries,
                        "cacheHitRate" to databaseStats.cacheHitRate,
                        "avgQueryTime" to databaseStats.avgQueryTime
                    )
                )
            }

            // Add a log entry
            post("/logs") {
                // In a real implementation, we would parse the request body
                // For now, just add a test log entry
                systemMonitorService.addLog(
                    LogEntry.Level.INFO,
                    "API服务",
                    "手动添加的日志条目"
                )
                call.respond(mapOf("success" to true))
            }
        }
    }
}